#include "head.h"

int recvN(int sockfd,void *buf,int length){
    int total = 0;//已接收文件长度
    char *p=(char *)buf;
    while(total<length){
        ssize_t sret=recv(sockfd,p+total,length-total,0);
        total+=sret;
    }
    return 0;
}

int recvFile(int netfd,char* fileName){
    //直接打开文件，如果一开始就存在则发送长度
    //如果一开始不存在就创建文件
    int fd=open(fileName,O_RDWR|O_CREAT|O_APPEND,0666);
    struct stat statbuf;
    fstat(fd,&statbuf);

    train_t train;

    //发送已有文件长度，若开始不存在文件则为0
    train.length=sizeof(statbuf.st_size);
    memcpy(train.data,&statbuf.st_size,train.length);
    send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);

    char buf[1024] = {0};
    int length;
    while(1){
        recvN(netfd,&length,sizeof(length));//接收文件长度
        if(length==0){
            break;
        }
        bzero(buf,sizeof(buf));//清空
        recvN(netfd,buf,length);//接收文件
        write(fd,buf,length);//写入本地
    }
    printf("%s download successfully\n",fileName);
    close(fd);
    return 0;
}

int uploadFile(int netfd,const char* fileName){
    int fd=open(fileName,O_RDONLY);
    
    train_t train;
    while(1){
        bzero(&train,sizeof(train));
        train.length=read(fd,train.data,sizeof(train.data));
        send(netfd,&train,sizeof(int)+train.length,MSG_NOSIGNAL);
        if(train.length==0){
            break;
        }
    }

    train.length=0;
    send(netfd,&train,sizeof(train.length)+train.length,MSG_NOSIGNAL);
    return 0;
}
